package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServiceResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by xinxuchu on 2018/10/10.
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public ServiceResponse<User> login(String username, String password) {

        //根据用户查询数据库中该用户名的数量
        int resultCount = userMapper.checkUsername(username);
        if (resultCount == 0) {
            return ServiceResponse.createByError("用户名不存在！");
        }

        //// TODO: 2018/10/13 MD5密码登录

        String MD5password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username, MD5password);
        if (user == null) {
            return ServiceResponse.createByError("密码错误！");
        }

        //user.setPassword("");//我平时写的代码
        user.setPassword(StringUtils.EMPTY);//将返回前端的密码置成空

        return ServiceResponse.createBySuccess("登录成功！", user);
    }

    public ServiceResponse<String> register(User user) {
//        int resultCount = userMapper.checkUsername(user.getUsername());
//        if (resultCount>0){
//            return ServiceResponse.createByError("用户名已存在！");
//        }
//        resultCount = userMapper.checkEmail(user.getEmail());
//        if (resultCount>0){
//            return ServiceResponse.createByError("email已被注册！");
//        }
        ServiceResponse<String> validResponse = this.checkValid(user.getUsername(), Const.USERNAME);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }
        validResponse = this.checkValid(user.getEmail(), Const.EMAIL);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //md5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        //insert語句返回的数值，是它成功的行数
        int resultCount = userMapper.insert(user);
        if (resultCount == 0) {
            return ServiceResponse.createByError("注册失败！");
        }
        return ServiceResponse.createBySuccess("注册成功！");

    }

    public ServiceResponse<String> checkValid(String str, String type) {
        //不是空的话，开始校验
        if (StringUtils.isNotBlank(type)) {
            if (Const.USERNAME.equals(type)) {
                int resultCount = userMapper.checkUsername(str);
                if (resultCount > 0) {
                    return ServiceResponse.createByError("用户名已存在！");
                }
            }
            if (Const.EMAIL.equals(type)) {
                int resultCount = userMapper.checkEmail(str);
                if (resultCount > 0) {
                    return ServiceResponse.createByError("email已被注册！");
                }
            }
        } else {
            return ServiceResponse.createByError("参数错误！");
        }
        return ServiceResponse.createBySuccess("校验成功！");
    }

    public ServiceResponse selectQuestion(String username) {

        ServiceResponse validResponse = this.checkValid(username, Const.USERNAME);
        if (validResponse.isSuccess()) {
            //说明用户名不存在
            return ServiceResponse.createByError("用户名不存在！");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if (StringUtils.isNotBlank(question)) {
            return ServiceResponse.createBySuccess(question);
        }
        return ServiceResponse.createByError("找回密碼的問題是空！");
    }

    public ServiceResponse<String> checkAnswer(String username, String question, String answer) {

        int resultCount = userMapper.checkAnswer(username, question, answer);
        if (resultCount > 0) {
            //說明語问题和答案是这个用户的，并且是正确的
            //我们需要获取用户的密码权限并设立一个有效期
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX + username, forgetToken);
            return ServiceResponse.createBySuccess(forgetToken);
        }
        return ServiceResponse.createByError("问题回答错误！");
    }

    public ServiceResponse<String> forgetRestPassword(String username, String passwordNew, String forgetToken) {
        if (StringUtils.isBlank(forgetToken)) {
            return ServiceResponse.createByError("参数错误，token需要传递！");
        }
        ServiceResponse validResponse = this.checkValid(username, Const.USERNAME);
        if (validResponse.isSuccess()) {
            //说明用户名不存在
            return ServiceResponse.createByError("用户名不存在！");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        if (StringUtils.isBlank(token)) {
            return ServiceResponse.createByError("token 无效或者过期！");
        }
//        String a= null;
//        if (a.equals("abc")){
//           //这种写法回报空指针异常的错误。
//        }
        if (StringUtils.equals(forgetToken, token)) {
            String MD5password = MD5Util.MD5EncodeUtf8(passwordNew);
            int rowcount = userMapper.updatePasswordByUsername(username, MD5password);
            if (rowcount > 0) {
                return ServiceResponse.createBySuccess("修改密码成功！");
            }
        } else {
            return ServiceResponse.createByError("token错误，请重新获取登陆密码token！");
        }
        return ServiceResponse.createByError("修改密码失败！");
    }

    public ServiceResponse<String> resetPassword(String passwordOld, String passwordNew, User user) {
        //防止横向越权，校验一下这个用户的旧密码一定是这个用户
        //这里考虑性能问题，一定会查个count出来，如果不指定用户，那么这更count一定是大于0的
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
        if (resultCount == 0) {
            return ServiceResponse.createByError("旧密码错误！");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        //会将数据库中的全部数据都更新一遍
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 0) {
            return ServiceResponse.createBySuccess("密码更新成功！");
        }
        return ServiceResponse.createByError("密码更新失败！");
    }

    public ServiceResponse<User> updateInfomation(User user) {
        //username是不能被更新的
        //email也要进行校验，检验email是否存在，并且存在的email若相同不能是当前用户的
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if (resultCount > 0) {
            return ServiceResponse.createByError("email已存在，请更换email再进行尝试！");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if (updateCount > 0) {
            return ServiceResponse.createBySuccess("更新个人对象信息成功", updateUser);
        }
        return ServiceResponse.createByError("更新个人信息失败！");
    }

    public ServiceResponse<User> getInformation(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return ServiceResponse.createByError("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServiceResponse.createBySuccess(user);
    }



    /**
     * 校验是否是管理员
     * @param user
     * @return
     */
    public ServiceResponse checkAdminRole(User user) {
        if (user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN) {
            return ServiceResponse.createBySuccess();
        }
        return ServiceResponse.createByError();
    }
}
